package com.shketai.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.shketai.entity.Majors;
import com.shketai.entity.Subject;

public class SubjectDao {

private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public int add(Subject subject,int major_id){
		Session session = sessionFactory.getCurrentSession();
		Majors majors = new Majors();
		majors.setId(major_id);
		subject.setMajors(majors);
		session.save(subject);
		return 1;
	}
	
	public int update(Subject subject){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Subject where id=:id");
		query.setInteger("id", subject.getId());
		List<Subject> list = query.list();
		Subject oldSubject = list.get(0);
		subject.setId(oldSubject.getId());
		subject.setMajors(oldSubject.getMajors());
		session.clear();
		session.update(subject);
		return 1;
	}
	public int delete(Subject subject){
		Session session = sessionFactory.getCurrentSession();
		session.delete(subject);
		return 1;
	}
	
	/**
	 * 选课时先查询所有课程
	 * @return
	 */
	public List<Subject> findAll(){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Subject ");
		List<Subject> list = query.list();
		return list;
	}
	
	/**
	 * 按照专业选课时先查询所有课程
	 * @return
	 */
	public List<Subject> findAll1(int major_id){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Subject where major_id=?  ");
		query.setInteger(0, major_id);
		List<Subject> list = query.list();
		if(list.size() > 0){
			return list;
		}else{
			return null;
		}
	}
	
	
}
